import request from '@/utils/request'

const getLocalCity = () => {
  return localStorage.getItem('current_city')
}

export const setLocalCity = city => {
  localStorage.setItem('current_city', JSON.stringify(city))
}

const BMap = window.BMap

export const getCurrentCity = () => {
  // 判断本地有没有，如果没有则调用百度地图定位的api
  const localCity = getLocalCity()

  if (localCity) {
    return Promise.resolve(JSON.parse(localCity))
  } else {
    return new Promise((resolve, reject) => {
      const myCity = new BMap.LocalCity()
      myCity.get(async result => {
        const res = await request.get(`area/info?name=${result.name}`)

        // 保存到本地
        setLocalCity(res.data.body)

        // 返回给需要的地方
        resolve(res.data.body)
      })
    })
  }
}
